@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>生产排产</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        .search-container {
            background: #fff;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .gantt-container {
            background: #fff;
            margin-bottom: 10px;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
            overflow-x: auto;
            overflow-y: hidden;
            max-width: 100%;
        }
        .table-container {
            background: #fff;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .search-form .layui-form-item {
            margin-bottom: 15px;
        }
        
        /* 甘特图样式 */
        .gantt-chart {
            min-width: 1740px;
            border-collapse: collapse;
            width: 100%;
            table-layout: fixed;
        }
        .gantt-chart th,
        .gantt-chart td {
            border: 1px solid #e6e6e6;
            padding: 8px;
            text-align: center;
            white-space: nowrap;
        }
        .gantt-chart th:nth-child(2),
        .gantt-chart td:nth-child(2) {
            width: 80px;
            min-width: 80px;
        }
        .gantt-chart th:nth-child(3),
        .gantt-chart td:nth-child(3) {
            width: 100px;
            min-width: 100px;
        }
        .gantt-chart th:nth-child(4),
        .gantt-chart td:nth-child(4) {
            width: 100px;
            min-width: 100px;
        }
        .gantt-chart th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .task-name {
            text-align: left !important;
            width: 240px;
            min-width: 240px;
            position: relative;
            padding: 8px 4px;
        }
        
        .task-title {
            display: inline-block;
            max-width: 130px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            vertical-align: middle;
        }
        
        /* 悬停提示框样式 */
        .task-name-tooltip {
            position: absolute;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 1000;
            max-width: 400px;
            word-wrap: break-word;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            display: none;
        }
        .task-name .expand-btn {
            cursor: pointer;
            margin-right: 5px;
            color: #1890ff;
        }
        .time-slot {
            width: 60px;
            height: 40px;
            position: relative;
            overflow: visible; /* 允许进度条溢出 */
            border: 1px solid #e6e6e6;
            text-align: center;
            padding: 4px;
        }
        .production-bar {
            height: 24px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 11px;
            font-weight: bold;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
            white-space: nowrap;
            overflow: hidden;
        }
        
        .production-bar-container {
            pointer-events: none;
            z-index: 10;
            white-space: nowrap;
        }
        .progress-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 10px;
            font-weight: bold;
            z-index: 1;
        }
        .completed-tag {
            background: #52c41a;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 11px;
            margin-left: 8px;
            font-weight: bold;
            display: inline-block;
            white-space: nowrap;
            box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
        }
        
        .status-tag {
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 11px;
            margin-left: 8px;
            font-weight: bold;
            display: inline-block;
            white-space: nowrap;
        }
        
        .status-tag.completed {
            background: #52c41a;
            color: white;
            box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
        }
        
        .status-tag.in-progress {
            background: #1890ff;
            color: white;
            box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
        }
        
        .status-tag.not-started {
            background: #8c8c8c;
            color: white;
            box-shadow: 0 2px 4px rgba(140, 140, 140, 0.3);
        }
        
        .status-tag.paused {
            background: #faad14;
            color: white;
            box-shadow: 0 2px 4px rgba(250, 173, 20, 0.3);
        }
        
        .status-tag.draft {
            background: #8c8c8c;
            color: white;
            box-shadow: 0 2px 4px rgba(140, 140, 140, 0.3);
        }
        
        .status-tag.confirmed {
            background: #1890ff;
            color: white;
            box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
        }
        
        /* 表格中的状态样式 */
        .status-draft {
            color: #8c8c8c;
            font-weight: bold;
        }
        
        .status-confirmed {
            color: #1890ff;
            font-weight: bold;
        }
        
        .status-completed {
            color: #52c41a;
            font-weight: bold;
        }
        
        .status-paused {
            color: #faad14;
            font-weight: bold;
        }
        
        .status-exception {
            color: #ff4d4f;
            font-weight: bold;
        }
        
        .sub-task {
            background-color: #fafafa;
        }
        .task-row:hover {
            background-color: #f5f5f5;
        }
        
        .task-row.completed {
            background-color: #f6ffed;
            border-left: 3px solid #52c41a;
        }
        
        .task-row.completed:hover {
            background-color: #d9f7be;
        }
        
        /* 详细表格样式 */
        .detail-table {
            margin-top: 20px;
        }
        .status-in-progress {
            color: #1890ff;
        }
        .status-completed {
            color: #52c41a;
        }
        .status-not-started {
            color: #8c8c8c;
        }
        
        /* 自定义滚动条样式 */
        .gantt-container::-webkit-scrollbar {
            height: 8px;
        }
        .gantt-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        .gantt-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        .gantt-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 表格中的排产按钮样式 */
        .scheduling-btn {
            background: #52c41a !important;
            border-color: #52c41a !important;
            font-size: 12px !important;
            padding: 2px 8px !important;
            height: 26px !important;
            line-height: 22px !important;
        }
        
        .scheduling-btn:hover {
            background: #73d13d !important;
            border-color: #73d13d !important;
        }
    </style>
</head>
<body>
    <div class="layui-container-fluid">
        <!-- 搜索条件区域 -->
        <div class="search-container">
            <form class="layui-form search-form" lay-filter="searchForm">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工单编码</label>
                            <div class="layui-input-block">
                                <input type="text" name="workOrderCode" placeholder="请输入工单编码" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工单名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="workOrderName" placeholder="请输入工单名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">来源单据</label>
                            <div class="layui-input-block">
                                <input type="text" name="sourceDocumentNo" placeholder="请输入来源单据" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品编码</label>
                            <div class="layui-input-block">
                                <input type="text" name="productCode" placeholder="请输入产品编码" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="productName" placeholder="请输入产品名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">客户编码</label>
                            <div class="layui-input-block">
                                <input type="text" name="customerCode" placeholder="请输入客户编码" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">客户名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="customerName" placeholder="请输入客户名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">需求日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="demandDateRange" placeholder="开始日期 - 结束日期" class="layui-input" id="demandDateRange">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="text-align: right; margin-left: 0;">
                                <button type="button" class="layui-btn" lay-submit lay-filter="searchBtn">
                                    <i class="layui-icon layui-icon-search"></i> 搜索
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="importBtn">
                                    <i class="layui-icon layui-icon-upload"></i> 导入
                                </button>
                                <button type="button" class="layui-btn layui-btn-warm" id="exportBtn">
                                    <i class="layui-icon layui-icon-export"></i> 导出
                                </button>
                                <button type="button" class="layui-btn" id="ganttDetailBtn" style="background: #1890ff; border-color: #1890ff;">
                                    <i class="layui-icon layui-icon-chart"></i> 进入甘特图详情
                                </button>
                                <button type="button" class="layui-btn layui-btn-danger" id="debugBtn" style="background: #ff7875; border-color: #ff7875;">
                                    <i class="layui-icon layui-icon-tips"></i> 数据状态诊断
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- 甘特图区域 -->
        <div class="gantt-container">
            <table class="gantt-chart">
                <thead>
                    <tr>
                        <th rowspan="3" class="task-name">任务名</th>
                        <th rowspan="3">工序</th>
                        <th rowspan="3">开始时间</th>
                        <th rowspan="3">结束时间</th>
                        <th colspan="15" style="background-color: #e8f4fd;">6月 14 - 6月 22</th>
                    </tr>
                    <tr>
                        <th colspan="3" style="border-bottom: 1px solid #e6e6e6;">6月 14</th>
                        <th colspan="3" style="border-bottom: 1px solid #e6e6e6;">6月 15</th>
                        <th colspan="3" style="border-bottom: 1px solid #e6e6e6;">6月 16</th>
                        <th colspan="3" style="border-bottom: 1px solid #e6e6e6;">6月 17</th>
                        <th colspan="3" style="border-bottom: 1px solid #e6e6e6;">6月 18</th>
                    </tr>
                    <tr>
                        <th style="width: 60px;">00:00</th>
                        <th style="width: 60px;">08:00</th>
                        <th style="width: 60px;">16:00</th>
                        <th style="width: 60px;">00:00</th>
                        <th style="width: 60px;">08:00</th>
                        <th style="width: 60px;">16:00</th>
                        <th style="width: 60px;">00:00</th>
                        <th style="width: 60px;">08:00</th>
                        <th style="width: 60px;">16:00</th>
                        <th style="width: 60px;">00:00</th>
                        <th style="width: 60px;">08:00</th>
                        <th style="width: 60px;">16:00</th>
                        <th style="width: 60px;">00:00</th>
                        <th style="width: 60px;">08:00</th>
                        <th style="width: 60px;">16:00</th>
                    </tr>
                </thead>
                <tbody id="ganttTableBody">
                    <!-- 甘特图数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>

        <!-- 详细数据表格区域 -->
        <div class="table-container">
            <!-- 数据表格 -->
            <table class="layui-hide" id="schedulingTable" lay-filter="schedulingTable"></table>
        </div>
    </div>



    <script>
        layui.use(['table', 'form', 'laydate', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;

            // 日期范围选择器
            laydate.render({
                elem: '#demandDateRange',
                type: 'date',
                range: true
            });

            // 使用自定义方式加载表格数据
            function loadTableData(searchParams = {}) {
                var queryData = {
                    workOrderCode: searchParams.workOrderCode || '',
                    workOrderName: searchParams.workOrderName || '',
                    productCode: searchParams.productCode || '',
                    productName: searchParams.productName || '',
                    customerCode: searchParams.customerCode || '',
                    customerName: searchParams.customerName || '',
                    demandDateStart: searchParams.demandDateStart || null,
                    demandDateEnd: searchParams.demandDateEnd || null,
                    page: searchParams.page || 1,
                    limit: searchParams.limit || 10
                };

                $.ajax({
                    url: '/ProductionScheduling/GetGanttData',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(queryData),
                    success: function(response) {
                        if (response.success && response.data) {
                            renderTable(response.data.listDate);
                        } else {
                            layer.msg(response.message || '加载数据失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('请求失败:', error);
                        layer.msg('请求失败，请检查网络连接');
                    }
                });
            }

            // 渲染表格数据
            function renderTable(data) {
                table.render({
                    elem: '#schedulingTable',
                    data: data,
                    page: true,
                    limits: [10, 20, 50, 100],
                    limit: 10,
                    loading: false,
                                    cellMinWidth: 80,
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'workOrderCode', title: '工单编码', width: 150, fixed: 'left'},
                        {field: 'workOrderName', title: '工单名称', width: 150},
                        {field: 'productCode', title: '产品编码', width: 120},
                        {field: 'productName', title: '产品名称', width: 120},
                        {field: 'productModel', title: '规格型号', width: 120},
                        {field: 'unit', title: '单位', width: 80},
                        {field: 'workOrderQuantity', title: '工单数量', width: 100},
                        {field: 'completedQuantity', title: '已生产数量', width: 120},
                        {field: 'progressPercent', title: '完成进度(%)', width: 120, templet: function(d) {
                            return d.progressPercent + '%';
                        }},
                        {field: 'productionStatusText', title: '生产状态', width: 100, templet: function(d) {
                            var statusClass = '';
                            // 状态映射：0=草稿，1=已确认，2=已完成
                            switch(d.productionStatus) {
                                case 0: statusClass = 'status-draft'; break;
                                case 1: statusClass = 'status-confirmed'; break;
                                case 2: statusClass = 'status-completed'; break;
                                default: statusClass = 'status-draft'; break;
                            }
                            return '<span class="' + statusClass + '">' + d.productionStatusText + '</span>';
                        }},
                        {field: 'demandDate', title: '需求日期', width: 120, templet: function(d) {
                            return layui.util.toDateString(new Date(d.demandDate), 'yyyy-MM-dd');
                        }},
                        {field: 'customerCode', title: '客户编码', width: 120},
                        {field: 'customerName', title: '客户名称', width: 120},
                        {title: '操作', width: 120, templet: function(d) {
                            return '<button class="layui-btn layui-btn-xs layui-btn-normal scheduling-btn" data-id="' + d.id + '" data-code="' + d.workOrderCode + '">' +
                                   '<i class="layui-icon layui-icon-add-circle"></i> 排产</button>';
                        }}
                    ]]
                });
            }

            // 初始化表格（先用测试数据）
            table.render({
                elem: '#schedulingTable',
                data: [ // 测试数据，用于初始显示
                    {
                        id: 1,
                        workOrderCode: 'MO20250620001',
                        workOrderName: '测100m',
                        workOrderSource: '客户订单',
                        orderNo: '155556',
                        productCode: 'CP00037',
                        productName: '测',
                        specification: '12',
                        unit: 'm',
                        workOrderQuantity: 100,
                        adjustedQuantity: 0,
                        completedQuantity: 0,
                        customerCode: 'C00008'
                    },
                    {
                        id: 2,
                        workOrderCode: 'MO20250621005',
                        workOrderName: 'A套餐',
                        workOrderSource: '客户订单',
                        orderNo: '0',
                        productCode: 'CP00025',
                        productName: 'A套餐',
                        specification: '个',
                        unit: 'PCS',
                        workOrderQuantity: 100,
                        adjustedQuantity: 0,
                        completedQuantity: 0,
                        customerCode: 'C00010'
                    },
                    {
                        id: 3,
                        workOrderCode: 'MO20250617005',
                        workOrderName: '剪切工单',
                        workOrderSource: '客户订单',
                        orderNo: '',
                        productCode: 'CP00059',
                        productName: '无菌钢管',
                        specification: '719*1.27',
                        unit: 'T',
                        workOrderQuantity: 4,
                        adjustedQuantity: 0,
                        completedQuantity: 0,
                        customerCode: 'C00012'
                    },
                    {
                        id: 4,
                        workOrderCode: 'MO20250617003',
                        workOrderName: '工单',
                        workOrderSource: '客户订单',
                        orderNo: '',
                        productCode: 'CP00025',
                        productName: '测试',
                        specification: '测',
                        unit: 'KG',
                        workOrderQuantity: 1,
                        adjustedQuantity: 0,
                        completedQuantity: 0,
                        customerCode: 'C00002'
                    }
                ],
                page: true,
                limits: [10, 20, 50, 100],
                limit: 10,
                loading: true,
                cellMinWidth: 80,
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'workOrderCode', title: '工单编码', width: 150, fixed: 'left'},
                    {field: 'workOrderName', title: '工单名称', width: 150},
                    {field: 'productCode', title: '产品编码', width: 120},
                    {field: 'productName', title: '产品名称', width: 120},
                    {field: 'productModel', title: '规格型号', width: 120},
                    {field: 'unit', title: '单位', width: 80},
                    {field: 'workOrderQuantity', title: '工单数量', width: 100},
                    {field: 'completedQuantity', title: '已生产数量', width: 120},
                    {field: 'progressPercent', title: '完成进度(%)', width: 120},
                    {field: 'productionStatusText', title: '生产状态', width: 100},
                    {field: 'demandDate', title: '需求日期', width: 120},
                    {field: 'customerCode', title: '客户编码', width: 120},
                    {field: 'customerName', title: '客户名称', width: 120},
                    {title: '操作', width: 120, templet: function(d) {
                        return '<button class="layui-btn layui-btn-xs layui-btn-normal scheduling-btn" data-id="' + (d.id || '') + '" data-code="' + (d.workOrderCode || '') + '">' +
                               '<i class="layui-icon layui-icon-add-circle"></i> 排产</button>';
                    }}
                ]]
            });

            // 搜索按钮事件
            form.on('submit(searchBtn)', function(data) {
                var searchData = {
                    workOrderCode: data.field.workOrderCode || '',
                    workOrderName: data.field.workOrderName || '',
                    productCode: data.field.productCode || '',
                    productName: data.field.productName || '',
                    customerCode: data.field.customerCode || '',
                    customerName: data.field.customerName || ''
                };
                
                // 处理日期范围
                if (data.field.demandDateRange) {
                    var dateRange = data.field.demandDateRange.split(' - ');
                    if (dateRange.length === 2) {
                        searchData.demandDateStart = dateRange[0];
                        searchData.demandDateEnd = dateRange[1];
                    }
                }
                
                // 同时更新甘特图和表格数据
                loadGanttData(searchData);
                loadTableData(searchData);
                return false;
            });

            // 重置按钮事件
            $('#resetBtn').click(function() {
                // 清空表单
                form.val('searchForm', {});
                
                // 重新加载默认数据
                loadGanttData();
                loadTableData();
            });

            // 进入甘特图详情按钮事件
            $('#ganttDetailBtn').click(function() {
                // 获取表格中选中的行
                var checkStatus = table.checkStatus('schedulingTable');
                var selectedData = checkStatus.data;
                
                if (selectedData.length === 0) {
                    // 如果没有选中任何行，使用默认工单ID直接跳转
                    var url = '/ProductionScheduling/GanttDetail?id=1';
                    window.location.href = url;
                } else if (selectedData.length === 1) {
                    // 选中一行，使用该行的ID跳转
                    var workOrderId = selectedData[0].id || 1;
                    var url = '/ProductionScheduling/GanttDetail?id=' + workOrderId;
                    window.location.href = url;
                } else {
                    // 选中多行，提示只能选择一行
                    layer.msg('请只选择一个工单查看详情', {icon: 2});
                }
            });

            // 表格中排产按钮事件处理（使用事件委托）
            $(document).on('click', '.scheduling-btn', function() {
                var workOrderId = $(this).data('id');
                var workOrderCode = $(this).data('code');
                
                // 从表格数据中找到对应的行数据
                var rowData = null;
                var tableData = table.cache.schedulingTable; // 获取表格缓存数据
                if (tableData && tableData.length > 0) {
                    rowData = tableData.find(function(item) {
                        return item.id == workOrderId;
                    });
                }
                
                // 构建URL参数，将工单数据传递给排产表单
                var urlParams = new URLSearchParams({
                    workOrderId: workOrderId || '',
                    workOrderCode: workOrderCode || ''
                });
                
                // 如果找到了行数据，添加对应ProductionSchedulingModel字段的参数用于回显
                if (rowData) {
                    // 对应ProductionSchedulingModel的字段
                    urlParams.append('workOrderName', rowData.workOrderName || '');        // WorkOrderName
                    urlParams.append('productCode', rowData.productCode || '');            // ProductCode  
                    urlParams.append('productModel', rowData.productModel || '');          // ProductModel
                    urlParams.append('workOrderQuantity', rowData.workOrderQuantity || 0); // WorkOrderQuantity
                    urlParams.append('customerCode', rowData.customerCode || '');          // 用于生成SourceDocumentNo
                    urlParams.append('processInfo', rowData.processInfo || '主工序');      // ProcessCode
                }
                
                layer.open({
                    type: 2,
                    title: '生产排产 - ' + workOrderCode,
                    shadeClose: true,
                    shade: 0.3,
                    maxmin: true,
                    area: ['900px', '600px'],
                    content: '/ProductionScheduling/SchedulingForm?' + urlParams.toString(),
                    success: function(layero, index) {
                        // 可以在这里添加iframe加载成功后的处理
                    },
                    end: function() {
                        // 关闭弹窗后刷新数据
                        loadGanttData();
                        loadTableData();
                    }
                });
            });

            // 数据状态诊断按钮事件
            $('#debugBtn').click(function() {
                $.ajax({
                    url: '/ProductionScheduling/CheckWorkOrderStatus',
                    type: 'POST',
                    success: function(response) {
                        if (response.success && response.data) {
                            var data = response.data;
                            layer.confirm(
                                '<div style="text-align: left;">' +
                                '<strong>数据库状态诊断结果：</strong><br/><br/>' +
                                '<strong>说明：</strong>' + data.说明 + '<br/><br/>' +
                                '<strong>当前筛选条件：</strong>' + data.当前应用服务筛选条件 + '<br/><br/>' +
                                '<strong>检查SQL：</strong><br/>' +
                                '<div style="background:#f5f5f5;padding:8px;margin:5px 0;border-radius:4px;font-family:monospace;">' +
                                data.建议检查SQL +
                                '</div>' +
                                '<strong>如果状态不是1，请执行：</strong><br/>' +
                                '<div style="background:#f5f5f5;padding:8px;margin:5px 0;border-radius:4px;font-family:monospace;">' +
                                data.如果状态不是1请执行 +
                                '</div>' +
                                '<strong>状态映射：</strong>' + data.状态映射说明 +
                                '</div>', {
                                icon: 1,
                                title: '数据库状态诊断',
                                area: ['600px', '400px'],
                                btn: ['我知道了']
                            });
                        } else {
                            layer.msg('获取诊断信息失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('请求失败', {icon: 2});
                    }
                });
            });

            // 加载甘特图数据（使用与表格相同的数据源）
            function loadGanttData(searchParams = {}) {
                var queryData = {
                    workOrderCode: searchParams.workOrderCode || '',
                    workOrderName: searchParams.workOrderName || '',
                    productCode: searchParams.productCode || '',
                    productName: searchParams.productName || '',
                    customerCode: searchParams.customerCode || '',
                    customerName: searchParams.customerName || '',
                    demandDateStart: searchParams.demandDateStart || null,
                    demandDateEnd: searchParams.demandDateEnd || null,
                    page: 1,
                    limit: 50 // 甘特图显示更多数据
                };

                $.ajax({
                    url: '/ProductionScheduling/GetGanttData',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(queryData),
                    success: function(response) {
                        if (response.success && response.data && response.data.listDate) {
                            renderGanttChart(response.data.listDate);
                        } else {
                            console.log('甘特图数据为空');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('加载甘特图数据失败:', error);
                    }
                });
            }
            
            // 渲染甘特图
            function renderGanttChart(data) {
                var tbody = $('#ganttTableBody');
                tbody.empty();
                
                if (!data || data.length === 0) {
                    tbody.append('<tr><td colspan="19" style="text-align: center; padding: 20px;">暂无数据</td></tr>');
                    return;
                }
                
                data.forEach(function(item) {
                    // 根据生产状态生成对应的状态标签（0=草稿，1=已确认，2=已完成）
                    var statusTag = '';
                    var statusIcon = '';
                    switch(item.productionStatus) {
                        case 0:
                            statusTag = '<span class="status-tag draft">草稿</span>';
                            statusIcon = '📄'; // 文档图标
                            break;
                        case 1:
                            statusTag = '<span class="status-tag confirmed">已确认</span>';
                            statusIcon = '✓'; // 确认图标
                            break;
                        case 2:
                            statusTag = '<span class="status-tag completed">✅ 已完成</span>';
                            statusIcon = '✅'; // 完成图标
                            break;
                        default:
                            statusTag = '<span class="status-tag draft">草稿</span>';
                            statusIcon = '📄';
                            break;
                    }
                    
                    // 显示四个关键字段：工单编码、工单名称、产品编码、产品名称
                    var taskTitle = item.workOrderCode + ' - ' + item.workOrderName + 
                                  ' (' + item.productCode + ' ' + item.productName + ')';
                    
                    var rowClass = 'task-row';
                    // 状态2代表已完成
                    if (item.productionStatus === 2) {
                        rowClass += ' completed';
                    }
                    
                    var row = '<tr class="' + rowClass + '">' +
                        '<td class="task-name" title="' + taskTitle + '">' +
                        '<i class="layui-icon layui-icon-triangle-d expand-btn"></i>' +
                        '<span class="task-title" data-full-title="' + taskTitle + '">' + taskTitle + '</span>' + statusTag +
                        '</td>' +
                        '<td>' + (item.processInfo || '主工序') + '</td>' +
                        '<td>' + (item.plannedStartTime ? layui.util.toDateString(new Date(item.plannedStartTime), 'yyyy-MM-dd') : 
                                  layui.util.toDateString(new Date(item.demandDate), 'yyyy-MM-dd')) + '</td>' +
                        '<td>' + (item.plannedEndTime ? layui.util.toDateString(new Date(item.plannedEndTime), 'yyyy-MM-dd') : 
                                  layui.util.toDateString(new Date(item.demandDate), 'yyyy-MM-dd')) + '</td>';
                    
                    // 计算进度条的跨度和位置
                    var totalSlots = 15;
                    
                    // 进度条显示的文本（按照图片格式）
                    var progressText = item.workOrderCode + ': ' + item.workOrderQuantity + 
                                     (item.unit || 'PCS') + ' 完成比例: ' + (item.progressPercent || 0) + '%';
                    
                    // 根据生产状态确定进度条颜色
                    var progressColor = '#52c41a'; // 默认绿色
                    if (item.productionStatus === 0) {
                        progressColor = '#8c8c8c'; // 草稿 - 灰色
                    } else if (item.productionStatus === 1) {
                        progressColor = '#1890ff'; // 已确认 - 蓝色
                    } else if (item.productionStatus === 2) {
                        progressColor = '#52c41a'; // 已完成 - 绿色
                    }
                    
                    // 计算进度条的实际位置和宽度
                    var ganttInfo = calculateGanttPosition(item);
                    
                    // 添加时间槽
                    for (var i = 0; i < totalSlots; i++) {
                        if (i === ganttInfo.startSlot) {
                            // 第一个进度条格子，包含跨列的进度条
                            row += '<td class="time-slot" style="position: relative;">' +
                                '<div class="production-bar-container" style="position: absolute; left: 0; top: 50%; transform: translateY(-50%); ' +
                                'width: ' + (ganttInfo.span * 100) + '%; height: 24px; z-index: 10;">' +
                                '<div class="production-bar" style="width: 100%; height: 100%; background: ' + progressColor + '; ' +
                                'border-radius: 4px; display: flex; align-items: center; justify-content: center; ' +
                                'color: white; font-size: 11px; font-weight: bold; white-space: nowrap; overflow: hidden;">' +
                                progressText +
                                '</div>' +
                                '</div>' +
                                '</td>';
                        } else if (i > ganttInfo.startSlot && i < ganttInfo.startSlot + ganttInfo.span) {
                            // 被进度条覆盖的格子，设置为透明
                            row += '<td class="time-slot" style="position: relative;"></td>';
                        } else {
                            // 普通空白格子
                            row += '<td class="time-slot"></td>';
                        }
                    }
                    
                    row += '</tr>';
                    tbody.append(row);
                });
                
                // 重新绑定展开/收起事件
                bindExpandEvents();
                
                // 绑定任务名悬停事件
                bindTaskNameHover();
            }
            
            // 计算甘特图进度条的位置和跨度
            function calculateGanttPosition(item) {
                // 甘特图时间基准：6月14日 00:00 到 6月18日 23:59
                var ganttStartDate = new Date('2025-06-14 00:00:00');
                var ganttEndDate = new Date('2025-06-18 23:59:59');
                
                // 获取任务的开始和结束时间
                var taskStartTime = item.plannedStartTime ? new Date(item.plannedStartTime) : new Date(item.demandDate);
                var taskEndTime = item.plannedEndTime ? new Date(item.plannedEndTime) : new Date(item.demandDate);
                
                // 如果任务时间超出甘特图范围，调整到甘特图范围内
                if (taskStartTime < ganttStartDate) taskStartTime = ganttStartDate;
                if (taskEndTime > ganttEndDate) taskEndTime = ganttEndDate;
                if (taskStartTime > ganttEndDate) taskStartTime = new Date(ganttEndDate.getTime() - 8 * 60 * 60 * 1000); // 前8小时
                if (taskEndTime < ganttStartDate) taskEndTime = new Date(ganttStartDate.getTime() + 8 * 60 * 60 * 1000); // 后8小时
                
                // 时间槽定义：每天3个时段，总共15个槽
                // 6月14日：0-00:00, 1-08:00, 2-16:00
                // 6月15日：3-00:00, 4-08:00, 5-16:00
                // 6月16日：6-00:00, 7-08:00, 8-16:00
                // 6月17日：9-00:00, 10-08:00, 11-16:00  
                // 6月18日：12-00:00, 13-08:00, 14-16:00
                
                function getTimeSlot(date) {
                    var day = date.getDate();
                    var hour = date.getHours();
                    
                    var baseSlot = 0;
                    if (day === 14) baseSlot = 0;
                    else if (day === 15) baseSlot = 3;
                    else if (day === 16) baseSlot = 6;
                    else if (day === 17) baseSlot = 9;
                    else if (day === 18) baseSlot = 12;
                    else return 0; // 默认
                    
                    if (hour < 8) return baseSlot;
                    else if (hour < 16) return baseSlot + 1;
                    else return baseSlot + 2;
                }
                
                var startSlot = getTimeSlot(taskStartTime);
                var endSlot = getTimeSlot(taskEndTime);
                
                // 确保至少跨越1个时间槽
                if (endSlot <= startSlot) {
                    endSlot = Math.min(startSlot + 1, 14);
                }
                
                var span = endSlot - startSlot + 1;
                
                return {
                    startSlot: startSlot,
                    span: span
                };
            }
            
            // 绑定甘特图展开/收起功能
            function bindExpandEvents() {
                $('.expand-btn').off('click').on('click', function() {
                    var $this = $(this);
                    if ($this.hasClass('layui-icon-triangle-d')) {
                        $this.removeClass('layui-icon-triangle-d').addClass('layui-icon-triangle-r');
                    } else {
                        $this.removeClass('layui-icon-triangle-r').addClass('layui-icon-triangle-d');
                    }
                });
            }
            
            // 绑定任务名悬停提示功能
            function bindTaskNameHover() {
                var $tooltip = null;
                
                $('.task-title').off('mouseenter mouseleave').on('mouseenter', function(e) {
                    var $this = $(this);
                    var fullTitle = $this.data('full-title');
                    
                    // 检查是否需要显示提示框（文本是否被截断）
                    if ($this[0].scrollWidth > $this[0].clientWidth) {
                        // 创建提示框
                        $tooltip = $('<div class="task-name-tooltip"></div>');
                        $tooltip.text(fullTitle);
                        $('body').append($tooltip);
                        
                        // 计算位置
                        var offset = $this.offset();
                        var tooltipWidth = $tooltip.outerWidth();
                        var windowWidth = $(window).width();
                        
                        var left = offset.left;
                        if (left + tooltipWidth > windowWidth) {
                            left = windowWidth - tooltipWidth - 10;
                        }
                        
                        $tooltip.css({
                            top: offset.top - $tooltip.outerHeight() - 5,
                            left: left,
                            display: 'block'
                        });
                    }
                }).on('mouseleave', function() {
                    if ($tooltip) {
                        $tooltip.remove();
                        $tooltip = null;
                    }
                });
            }
            
            // 页面加载时初始化甘特图和表格数据
            loadGanttData();
            loadTableData();
        });
    </script>
</body>
</html> 